package com.xhwl.logistics.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.common.dto.cent.vehicle.SupplierConfigDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.vehicle.ParkSupplierEnum;
import com.xhwl.common.enums.vehicle.SyncTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.query.cent.device.DeviceQuery;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.vo.cent.vehicle.SyncVO;
import com.xhwl.logistics.service.cent.IDeviceService;
import com.xhwl.logistics.service.cent.IProductAccessCentService;
import com.xhwl.logistics.strategy.BasicInfoSyncStrategy;
import com.xhwl.logistics.strategy.InfoSyncSupplierStrategy;
import com.xhwl.logistics.strategy.context.InfoSyncSupplierStrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 基础信息设备同步实现类
 * @author: lu.Aaron
 * @create: 2021-06-30 09:54
 **/
@Slf4j
//@Component
public class BasicInfoDeviceSyncServiceImpl  implements BasicInfoSyncStrategy {
    @Autowired
    private InfoSyncSupplierStrategyContext infoSyncSupplierStrategyContext;

    @Autowired
    private IProductAccessCentService productAccessCentService;
    @Autowired
    private IDeviceService deviceService;

    @Override
    public int getSyncType() {
        return SyncTypeEnum.DEVICE.type;
    }

    @Override
    public ResultJson basicInfoSync(Short industryId, SyncVO syncVO) {
        log.info("同步车场设备开始(sync parking device start)");

        //先根据项目id和产品分类id查询供应商
        @NotNull Integer projectId = syncVO.getProjectId();
        @NotNull String parkId = syncVO.getParkId();
        @NotEmpty String projectName = syncVO.getProjectName();
        List<DeviceProjSupplierCategory> deviceProjSupplierCategories = productAccessCentService.listProductAccess(industryId, new ProductAccessQuery(projectId, CategoryEnum.YARD_GATE.getId()));
        if (deviceProjSupplierCategories.isEmpty()) {
            throw new BusinessException("该项目未配置供应商，请先配置");
        }
        DeviceProjSupplierCategory productAccess = deviceProjSupplierCategories.get(0);
        JSONObject properties = productAccess.getProperties();
        //获取供应商配置信息
        SupplierConfigDTO supplierConfigDTO = JSON.toJavaObject(properties, SupplierConfigDTO.class);
        //根据supplierId以及策略模式选取对应的接口实现类
        Integer supplierId = productAccess.getSupplierId();

        InfoSyncSupplierStrategy infoSyncSupplierService = infoSyncSupplierStrategyContext.getInfoSyncSupplierService(ParkSupplierEnum.getParkSupplierEnum(supplierId));
        //DeviceDTO deviceDTO =new DeviceDTO();
        //deviceDTO.setParkId(parkId);
        Map<String, Object> map = new HashMap<>();
        map.put("parkId",parkId);
        List<Device> listFromSupplier = infoSyncSupplierService.getParkingLotDevice(map,supplierConfigDTO);
        if (listFromSupplier.isEmpty()) {
            throw new BusinessException("查询供应商，无相关设备信息");
        }
        listFromSupplier.forEach(l->{
            l.setProjectId(projectId);

            //cent-common修改Device setCategoryId
            //车行系统的类型id为3
            l.setCategoryId(3);

        });
        //判断查询到的设备是否已经在数据库了，在就不新增，不在就新增
        List<String> thirdDeviceIdsFromSupplier = listFromSupplier.stream().map(a -> a.getThirdDeviceId()).collect(Collectors.toList());
        DeviceQuery query = new DeviceQuery();
        query.setProjectId(projectId);
        query.setThirdDeviceIdList(thirdDeviceIdsFromSupplier);
        List<com.xhwl.common.dto.cent.device.DeviceDTO> listFromDB = deviceService.list(industryId, query);
        if (null==listFromDB||listFromDB.isEmpty()) {
            //直接新增
            deviceService.batchSave(industryId,listFromSupplier);
        }else{

            //判断listFromDB与listFromSupplier关系，是则要找出补集，差集，再新增或删除
            List<String> thirdDeviceIdFromDB = listFromDB.stream().map(l -> l.getThirdDeviceId()).collect(Collectors.toList());
            //需要删除的情况
            List<String> deleteList = new ArrayList<>();
            listFromDB.forEach(l->{
                if (!thirdDeviceIdsFromSupplier.contains(l.getThirdDeviceId())) {
                    //说明数据需要删除该数据
                    deleteList.add(l.getThirdDeviceId());

                }
            });
            if (!deleteList.isEmpty()) {
                List<Device> list = new ArrayList<>();
                deleteList.forEach(d->{
                    Device device = new Device();
                    device.setThirdDeviceId(d);
                    list.add(device);
                });
                deviceService.BatchDelete(industryId,list);

            }
            //需要新增的情况
            List<Device> insertList = new ArrayList<>();

            listFromSupplier.forEach(l->{
                if (!thirdDeviceIdFromDB.contains(l.getThirdDeviceId())) {
                    insertList.add(l);
                }
            });
            deviceService.batchSave(industryId,insertList);

        }

        log.info("同步车场设备结束(sync parking device end)");
        return ResultJson.success("同步设备成功");

    }
}

